package com.mbuswidget;

import android.app.Activity;
import android.app.AlertDialog;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MBusWidgetConfigurationStopsAddStopByRouteStop extends Activity {
	private MBusWidgetService mbusBoundService;
	
	MBusInfo mbusInfo;
	Integer routeIndex;
	int widgetID;

	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			// This is called when the connection with the service has been
			// established, giving us the service object we can use to
			// interact with the service. Because we have bound to a explicit
			// service that we know is running in our own process, we can
			// cast its IBinder to a concrete class and directly access it.
			mbusBoundService = ((MBusWidgetService.LocalBinder) service)
					.getService();
//			mService = new Messenger((MBusWidgetService.LocalBinder)service);

	        
//			// Tell the user about this for our demo.
//			Toast.makeText(MBusWidgetConfigurationStopsAddStopByRouteStop.this,
//					R.string.local_service_connected, Toast.LENGTH_SHORT)
//					.show();
			
	        ShowResults();
		}

		public void onServiceDisconnected(ComponentName className) {
			// This is called when the connection with the service has been
			// unexpectedly disconnected -- that is, its process crashed.
			// Because it is running in our same process, we should never
			// see this happen.
			mbusBoundService = null;
			
	        // This is called when the connection with the service has been
	        // unexpectedly disconnected -- that is, its process crashed.

//			Toast.makeText(MBusWidgetConfigurationStopsAddStopByRouteStop.this,
//					R.string.local_service_disconnected, Toast.LENGTH_SHORT)
//					.show();
		}
	};
	private boolean mIsBound;

	void doBindService() {
		// Establish a connection with the service. We use an explicit
		// class name because we want a specific service implementation that
		// we know will be running in our own process (and thus won't be
		// supporting component replacement by other applications).
		bindService(
				new Intent(MBusWidgetConfigurationStopsAddStopByRouteStop.this, MBusWidgetService.class),
				mConnection, Context.BIND_AUTO_CREATE);
		mIsBound = true;
	}

	void doUnbindService() {
		if (mIsBound) {
			// Detach our existing connection.
			unbindService(mConnection);
			mIsBound = false;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.selectstopby);

		routeIndex = getIntent().getIntExtra(MBusWidgetConstants.SELECTED_ROUTE, MBusWidgetConstants.INVALID_ROUTE);
		
		if(routeIndex == MBusWidgetConstants.INVALID_ROUTE) {
			finish();
		}
		
		widgetID = getIntent().getIntExtra(
				AppWidgetManager.EXTRA_APPWIDGET_ID,
				AppWidgetManager.INVALID_APPWIDGET_ID);
		
		if(widgetID == AppWidgetManager.INVALID_APPWIDGET_ID) {
			finish();
		}
		
		TextView topLbl = (TextView)findViewById(R.id.Toplbl);
		topLbl.setText(R.string.chooseStop);
		
		mIsBound = false;

//		 startService(new Intent(MBusWidgetActivity.this,
//		 MBusWidgetService.class));

		
		doBindService();
	}
	
	private void ShowResults() {
		mbusInfo = null;
		
		if(mbusBoundService != null) {
			mbusInfo = mbusBoundService.getBusInfo();
		}
		
		if (mbusInfo == null) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Cannot connect to MBus XML server")
					.setCancelable(true);
			AlertDialog alert = builder.create();
			alert.show();
			// System.exit(0);
		} else {
			// int numOfRoutes = mBusInfoDoc.getElementsByTagName("livefeed")
			// .getLength();
			ListView lv = (ListView) findViewById(R.id.itemList);

			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1);
			lv.setAdapter(adapter);

			BusRoute route = mbusInfo.getRoutes().get(routeIndex);
			
			adapter.clear();
			for (int i = 0; i < route.getNumberOfStops(); i++) {
				adapter.add(route.getStops().get(i).getShortName());
			}

			lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				public void onItemClick(AdapterView<?> av, View v, int pos,
						long id) {
					// TODO Auto-generated method stub
					// { Work=please } <bus lines 1< but>1000 :)
					
					Intent intent = getIntent();
					
					String[] stringArray = new String[1];
					stringArray[0] = mbusInfo.getRoutes().get(routeIndex).getStops().get(pos).getShortName();
					intent.putExtra(MBusWidgetConstants.INTENT_SELECTED_STOPS, stringArray);
					intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetID);
					intent.putExtra(MBusWidgetConstants.STOP_TYPE, MBusWidgetConstants.ADD_STOP);
					
					setResult(Activity.RESULT_OK, intent);
					doUnbindService();
					finish();
				}
			});
		}	
	}
}
